const App = getApp()
import { CartModel } from '../../../models/cart.js'
const ModelCart = new CartModel()
import { HomeModel } from '../../../models/home.js'
const ModelHome = new HomeModel()
import $CountDown from '../../../utils/countdown.js'
Page({
  data: {
    cartStatus: 2, // 购物车状态：1APP，2小程序
    cartList: null,
    selectedAll: false,
    totalFee: 0,
    selectedCounter: 0,
    showTabbar: true,
    allDis: false,
    iphoneX: App.globalData.isIphoneX,
    advertsStr: '',
    advertsStatus: 0,
    statusBarHeight: App.globalData.statusBarHeight,
    minBanner: [],
    hours: 0,
    min: 0,
    sec: 0
  },
  onLoad: function(options) {
    const from = options.from
    // 从商品详情页来不显示底部tabbar
    if (from == 'goods') {
      this.setData({
        showTabbar: false
      })
    }
    this.getBannerList()
  },
  onShow() {
    this.initData()
  },
  // 倒计时结束触发
  countdownEnd() {
    this.initData()
  },
  // 获取购物车数据
  initData() {
    ModelCart.getShopCart({ status: this.data.cartStatus })
      .then(res => {
        const cartData = res.data.cartList
        let cartCount = 0
        let stateCount = 0
        cartData.forEach(item => {
          // 专场下架了
          item.checked = false
          // 循环商品
          let count = 0
          item.goodsList.forEach(goods => {
            goods.checked = false
            // 库存为零,专场下架，专场不是正在进行中,商品下架
            if (goods.availableStock == 0 || item.specialState == 0 || item.specialStatus !== 2 || goods.goodsStatus == 0) {
              goods.disabled = true
              count++
            }
          })
          // 所有库存为空
          if (count === item.goodsList.length) {
            item.disabled = true
            cartCount++
          }
        })
        // 所有的专场不可用,专场下架
        if (cartCount === cartData.length) {
          this.setData({
            allDis: true
          })
        }
        const adverts = res.data.adverts
        // 是否显示全场包邮
        let advertsStr = ''
        if (adverts.state == 1) {
          // type 类型：1全场满多少件，2全场满多少金额
          if (adverts.type == 1) {
            advertsStr = '全场满' + adverts.first
            if (adverts.freight == 0) {
              advertsStr += '件包邮'
            } else {
              advertsStr += '件运费' + (adverts.freight / 100).toFixed(2)
            }
            // 满金额
          } else {
            advertsStr = '全场满' + (adverts.first / 100).toFixed(2)
            if (adverts.freight == 0) {
              advertsStr += '元包邮~'
            } else {
              advertsStr += '元运费' + (adverts.freight / 100).toFixed(2)
            }
          }
        }

        this.setData({
          cartList: cartData,
          selectedAll: false,
          totalFee: 0,
          selectedCounter: 0,
          advertsStr: advertsStr,
          advertsStatus: adverts.state
        })
        // const cartList = this.data.cartList
        // for(var i in cartList){
        //   if(cartList[i].activityType == 2){
        //     console.log('i:'+i)
        //     this.seckillCountdown(cartList[i].endDate)
        //   }
        // }

        // 结束下来刷新
        wx.stopPullDownRefresh()
      })
      .catch(err => {})
  },
  // 选择商品
  checkedGoods(e) {
    // const checked = e.currentTarget.dataset.checked
    // 活动index
    const sIndex = e.currentTarget.dataset.sindex
    // 商品index
    const gIndex = e.currentTarget.dataset.gindex
    // 活动
    const store = this.data.cartList[sIndex]
    // 商品
    const goods = this.data.cartList[sIndex].goodsList[gIndex]
    goods.checked = !goods.checked
    let count = 0
    let totalNum = 0
    this.data.cartList[sIndex].goodsList.forEach(pro => {
      totalNum++
      if (pro.checked) return count++
    })
    // 商品数等于总数 活动全选
    if (count === totalNum) {
      this.checkedStore(sIndex)
    } else {
      store.checked = false
      this.data.selectedAll = false
      // 更新数据
      this._resetCartData()
    }
  },
  checkedStore(e) {
    let sIndex = null
    if (e.currentTarget) {
      // 页面点击事件触发
      sIndex = e.currentTarget.dataset.sindex
    } else {
      // 其他方法触发
      sIndex = e
    }
    // 活动
    const store = this.data.cartList[sIndex]
    store.checked = !store.checked
    // 全选仓库下的所有商品
    store.goodsList.forEach(item => {
      item.checked = store.checked
    })
    let count = 0
    // 当活动全选的总个数等于所有活动个数是全选
    this.data.cartList.forEach(item => {
      if (item.checked) return count++
    })
    if (count === this.data.cartList.length) {
      this.selectedAllGoods()
    } else {
      this.data.selectedAll = false
    }
    this._resetCartData()
  },
  // 选择所有
  selectedAllGoods() {
    this.data.cartList.forEach(store => {
      store.checked = !this.data.selectedAll
      store.goodsList.forEach(goods => {
        goods.checked = !this.data.selectedAll
      })
    })
    this.data.selectedAll = !this.data.selectedAll
    this._resetCartData()
  },
  // 合计费用
  computedTotalFee() {
    let computedFee = 0
    let selectedCounter = 0
    this.data.cartList.forEach(store => {
      // 如果是进行中的状态
      if (store.specialStatus === 2 && store.specialState !== 0) {
        store.goodsList.forEach(goods => {
          if (goods.checked && !goods.disabled) {
            computedFee += goods.cartNum * (goods.goodsMoney - goods.reliefMoney)
            selectedCounter += goods.cartNum
          }
        })
      }
    })
    this.data.selectedCounter = selectedCounter
    this.data.totalFee = computedFee
  },
  // 更新购物车商品数据
  _resetCartData() {
    // 合计费用
    this.computedTotalFee()
    this.setData({
      cartList: this.data.cartList,
      selectedAll: this.data.selectedAll,
      totalFee: this.data.totalFee,
      selectedCounter: this.data.selectedCounter
    })
  },
  // 删除购物车商品
  delGoods(e) {
    const cartId = e.currentTarget.dataset.id
    // 活动index
    const sIndex = e.currentTarget.dataset.sindex
    // 商品index
    const gIndex = e.currentTarget.dataset.gindex
    // 转数组，参数数组形式
    const cartArr = []
    cartArr.push(cartId)
    // 删除操作
    ModelCart.delCartGoods({ cartId: cartArr })
      .then(res => {
        this.initData()
        // 更新购物车商品数据
        this._resetCartData()
        // 数组中删除
        // if (res.status === 200) {
        //   // 成功
        //   if (this.data.cartList[sIndex].goodsList.length <= 1) {
        //     this.data.cartList.splice(sIndex, 1)
        //   } else {
        //     this.data.cartList[sIndex].goodsList.splice(gIndex, 1)
        //   }
        //   this._resetCartData()
        // } else {
        //   //失败
        //   App.WxService.showToast({ title: res.info, icon: 'none' })
        // }
      })
      .catch()
  },
  trigger(e) {
    const type = e.detail.type
    // 最多
    if (type === 'add') {
      App.WxService.showToast({ title: '不能再多了哦', icon: 'none' })
      return false
    }
    // 最少
    if (type === 'sub') {
      App.WxService.showToast({ title: '不能再少了哦', icon: 'none' })
      return false
    }
  },
  // 修改数量
  changeGoodsNum(e) {
    const cartId = e.currentTarget.dataset.id
    // 活动index
    const sIndex = e.currentTarget.dataset.sindex
    // 商品index
    const gIndex = e.currentTarget.dataset.gindex
    // 商品
    const goods = this.data.cartList[sIndex].goodsList[gIndex]
    var num = e.detail.value
    ModelCart.updateGoodsNum({
      cartId: cartId,
      cartNum: num
    })
      .then(res => {
        goods.cartNum = num
        // 更新购物车商品数据
        this._resetCartData()
      })
      .catch()
  },
  // 去详情
  goGoodsDetail(e) {
    const goodsId = e.currentTarget.dataset.id
    // const specialCode = e.currentTarget.dataset.scode
    const status = e.currentTarget.dataset.status
    // 不是活动中的不能点
    if (status) {
      return false
    }
    // 专场模式
    App.WxService.navigateTo(`/pages/goodsDetail/index?id=${goodsId}`)
    // if (specialCode) {
    //   App.WxService.navigateTo(
    //     `/pages/goodsDetail/index?id=${goodsId}&scode=${specialCode}`
    //   )
    // } else {
    //   App.WxService.navigateTo(`/pages/goodsDetail/index?id=${goodsId}`)
    // }
  },

  // 去活动
  goActivity(e) {
    const specialCode = e.currentTarget.dataset.scode
    const specialStatus = e.currentTarget.dataset.status
    // 不是活动中的不能点
    if (specialStatus !== 2) {
      return false
    }
    App.WxService.navigateTo(`/pages/activity/index?scode=${specialCode}`)
  },
  // 随便逛逛去首页
  goHome() {
    App.WxService.navigateTo('/pages/home/index')
  },

  // 提交购物车
  goOrder() {
    const cartIdsArr = []
    this.data.cartList.forEach(store => {
      store.goodsList.forEach(goods => {
        if (goods.checked && !goods.disabled) {
          cartIdsArr.push(goods.id)
        }
      })
    })
    if (cartIdsArr.length <= 0) {
      App.WxService.showToast({ title: '请选择结算商品', icon: 'none' })
      return
    }
    const cartIds = cartIdsArr.join(',')
    App.WxService.navigateTo(`/packCart/pages/payOrder/index?ids=${cartIds}`)
    //   // ModelCart.submitCart({
    //   //   cartId: cartIds
    //   // }).then(res => {})
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.onShow()
  },
  //获取轮播列表
  getBannerList() {
    const self = this
    const params = {}
    ModelHome.queryCrazy()
      .then(res => {
        self.setData({
          minBanner: res.data.classList // 小轮播
        })
      })
      .catch(err => {})
  }
})
